package fromnet;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;

public class DBReader {

	private static String DATABASE_FILE = "file:///E:/Data/Applications/Book/ArtistDatabase.db";
	private FileConnection fc;
	private InputStream fis;
	private boolean fileDone = false;
	private boolean processDone = false;
	private String currentString = null;

	public DBReader() throws IOException {
		fc = (FileConnection) Connector.open(DATABASE_FILE);

		if (!fc.exists()) {
			throw new IOException("File does not exists");
		}
		fis = fc.openInputStream();
	}

	public String getNextRecord() throws IOException {
		if (processDone) {
			throw new IOException("No more record.");
		}
		String record = null;
		if (currentString == null) {
			currentString = readFromFile();
		}
		int returnIndex = currentString.indexOf("\r\n");
		if ((returnIndex < 0) && (!fileDone)) {
			currentString += readFromFile();
			record = currentString.substring(0, returnIndex);
			currentString = currentString.substring(returnIndex + 2);
		} else if ((returnIndex < 0) && fileDone) {
			record = currentString;
			processDone = true;
		} else {
			record = currentString.substring(0, returnIndex);
			currentString = currentString.substring(returnIndex + 2);
		}
		// OK calcul du done
		// OK refabrication du currentstring
		// OK fabrication du record
		// OK exception
		return record;
	}

	private String readFromFile() throws IOException {
		String result = null;
		byte[] b = new byte[1024];
		int length = fis.read(b, 0, 128);

		if (length > 0) {
			result = new String(b, 0, length);
		} else {
			fileDone = true;
			fis.close();
			fc.close();
		}
		return result;
	}

	public boolean isDone() {
		return fileDone;
	}
}
